<script setup>
import { ref, watch } from 'vue';
import api from '@/api';
const props = defineProps({
    show: {
        type: Boolean,
        default: false
    }
});

watch(
    () => props.show,
    (val) => {
        if (val) {
            getAllProvinces();
        }
        showCascader.value = val;
        curSelectedOptions.value = [];
    }
);

const emit = defineEmits(['confirm', 'close']);
const showCascader = ref(props.show);
const cascaderOptions = ref([]);
const cascaderValue = ref('');
const curSelectedOptions = ref([]);
const selectedValue = ref([]);

const onCascaderClose = () => {
    emit('close');
    showCascader.value = false;
};

const onCascaderConfirm = () => {
    if (curSelectedOptions.value.length < 3) return;
    emit('confirm', selectedValue.value);
    showCascader.value = false;
};

const onCascaderChange = ({ selectedOptions }) => {
    const { code, level, codeId } = selectedOptions[selectedOptions.length - 1];

    curSelectedOptions.value = selectedOptions;
    if (level === 1) {
        getCityById(code);
    } else if (level === 2) {
        getAreaById(codeId);
    }
};

const onCascaderFinish = ({ selectedOptions }) => {
    selectedValue.value = selectedOptions.map((option) => option.name);
};

/**
 *
 * 获取全国全部省份
 * @returns
 */
const getAllProvinces = () => {
    api.fetchGet('queryAddressAllProvince', {}, { isLoading: false }).then((data) => {
        const curData = data.map((item) => ({
            ...item,
            children: [],
            level: 1
        }));
        cascaderOptions.value = curData || [];
    });
};
/**
 * 通过省份id获取省份对应的城市
 * @param {*} parentCode
 * @param {*} callback
 * @returns
 */
const getCityById = (parentCode) => {
    api.fetchGet('queryAddressByParentId', { parentId: parentCode, level: 2 }).then((data) => {
        const curData = data.map((item) => ({
            ...item,
            codeId: item.code,
            code: item.code == parentCode ? parentCode + 'x1' : item.code,
            children: [],
            level: 2
        }));
        const curParentData = cascaderOptions.value.find((item) => item.code === parentCode);
        if (curParentData && curParentData.children.length === 0) {
            curParentData.children = curData;
        }
    });
};
/**
 * 通过城市id获取城市对应的区域
 * @param {*} parentId
 * @param {*} callback
 * @returns
 */
const getAreaById = (parentCode) => {
    api.fetchGet('queryAddressByParentId', { parentId: parentCode, level: 3 }).then((data) => {
        const curData = data.map((item) => ({
            ...item,
            level: 3
        }));
        const firstParent = curSelectedOptions.value[0] || {};
        const secondParent = curSelectedOptions.value[1] || {};
        const curLevel1Data = cascaderOptions.value.find((item) => item.code === firstParent.code);
        const curLevel2Data = curLevel1Data.children.find(
            (item) => item.code === secondParent.code
        );
        if (curLevel2Data && curLevel2Data.children.length === 0) {
            curLevel2Data.children = curData;
        }
    });
};
</script>

<template>
    <van-popup
        v-model:show="showCascader"
        position="bottom"
        round
        class="c-region-popup"
        close-on-click-overlay
        close-icon-position="top-left"
        @click-overlay="onCascaderClose"
    >
        <div class="popup-header">
            <div class="left" @click="onCascaderClose">
                <c-icon name="close" size="24" color="#1a1a1a"></c-icon>
            </div>
            <div class="title">所在地区</div>
            <div
                :class="`right ${curSelectedOptions.length < 3 ? 'btn-disabled' : ''}`"
                @click="onCascaderConfirm"
            >
                确定
            </div>
        </div>
        <van-cascader
            class="cascader-box"
            :show-header="false"
            v-model="cascaderValue"
            active-color="#07C160"
            :field-names="{ text: 'name', value: 'code', children: 'children' }"
            :options="cascaderOptions"
            @close="showCascader = false"
            @change="onCascaderChange"
            @finish="onCascaderFinish"
        />
    </van-popup>
</template>

<style lang="less" scoped>
@import '../../styles/variables.less';
@import '../../styles/mixin.less';
.c-region-popup {
    box-sizing: border-box;
    height: 75%;
    background-color: #f6f6f6;
}
.popup-header {
    width: 100%;
    height: 56px;
    padding: 0 16px;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: @white;

    .left,
    .right {
        width: 52px;
        height: 28px;
        line-height: 28px;
        display: flex;
        align-items: center;
    }

    .title {
        flex: 1;
        text-align: center;
        font-size: 17px;
        color: @label-color;
        font-weight: 500;
    }

    .right {
        box-sizing: border-box;
        background-color: @primary-color;
        color: @white;
        border-radius: 6px;
        font-size: 14px;
        font-weight: 500;
        justify-content: center;
    }

    .btn-disabled {
        color: @white;
        background-color: @disabled-color;
    }
}

.cascader-box {
    height: calc(100% - 56px);
    background-color: @white;
    overflow: hidden;
}

::v-deep(.van-cascader__options) {
    box-sizing: border-box;
    height: 430px;
    padding-bottom: calc(60px + constant(safe-area-inset-bottom));
    padding-bottom: calc(60px + env(safe-area-inset-bottom));

    .van-cascader__option {
        height: 52px;
        line-height: 52px;
        color: @label-color;
        padding: 0 16px;
    }
}
</style>
